<!--
 * @Description: 组织人员-列表
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2024-03-05
 * @LastEditors: 何伟伦 weilun@ssc-hn.com
 * @LastEditTime: 2024-05-11
-->
<template>
  <div class="ssc-list org-person-list">
    <div class="org">
      <div class="org-title">组织架构</div>
      <a-tree v-if="dept.visible" :tree-data="dept.datas" :defaultExpandAll="true" @select="dept.onSelect">
        <template #title="{ title }">{{ title }}</template>
      </a-tree>
    </div>
    <div class="content">
      <div class="ssc-search">
        <a-row :gutter="24">
          <a-col :span="6">
            <a-form-item label="姓名">
              <a-input v-model:value="searchParam.userName" placeholder="请输入姓名" :maxlength="20" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="手机号">
              <a-input v-model:value="searchParam.userPhone" placeholder="请输入手机号" :maxlength="11" type="number" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-row justify="end">
              <a-button @click="clear()">重置</a-button>
              <a-button class="ml-4" type="primary" @click="search()">查询</a-button>
            </a-row>
          </a-col>
        </a-row>
      </div>
      <div class="ssc-table">
        <div class="ssc-table-header">
          <span class="ssc-table-header-title">组织人员</span>
          <a-button type="primary" @click="add()">
            <template #icon><plus-outlined :style="{ 'font-weight': 'bold' }" /></template>
            添加
          </a-button>
        </div>
        <a-table :columns="table.columns" :data-source="dataList" :loading="loading" :pagination="pagination" @change="onPaginationChange">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'userName'">
              <a-button type="primary" class="dept-leader" v-if="record.isDeptLeader == 1">负责人</a-button>
              {{ record.userName }}
            </template>
            <template v-if="column.key === 'userStatus'">
              <span>
                <a-tag v-if="record.userStatus === 1" color="green"> 正常 </a-tag>
                <a-tag v-else color="volcano"> 冻结 </a-tag>
              </span>
            </template>
            <template v-if="column.key === 'action'">
              <span>
                <a @click="edit(record)">编辑</a>
                <a-divider type="vertical" />
                <a @click="setLeader(record)">指定上级</a>
                <a-divider type="vertical" />
                <template v-if="noDeptLeader">
                  <a-popconfirm title="是否要设为负责人?" ok-text="是" cancel-text="否" @confirm="setDeptLeader(record, DoTypeEnum.SET)">
                    <a>设为负责人</a>
                  </a-popconfirm>
                  <a-divider type="vertical" />
                </template>
                <template v-else-if="record.isDeptLeader == 1">
                  <a-popconfirm title="是否要取消负责人?" ok-text="是" cancel-text="否" @confirm="setDeptLeader(record, DoTypeEnum.CANCEL)">
                    <a>取消负责人</a>
                  </a-popconfirm>
                  <a-divider type="vertical" />
                </template>
                <a @click="setPosition(record)">岗位设置</a>
                <a-divider type="vertical" />
                <a-popconfirm :title="`是否要${record.userStatus === 1 ? '冻结' : '恢复'}该人员?`" ok-text="是" cancel-text="否" @confirm="setStatus(record)">
                  <a>{{ record.userStatus === 1 ? '冻结' : '恢复' }}</a>
                </a-popconfirm>
              </span>
            </template>
          </template>
        </a-table>
      </div>
    </div>
    <div class="modal">
      <Add v-model:visible="modalAdd.visible" :depts="dept.datas" @success="modalAdd.success" />
      <Edit v-model:visible="modalEdit.visible" :depts="dept.datas" :data="table.selectedRecord" @success="modalEdit.success" />
      <Leader v-model:visible="modalLeader.visible" :depts="dept.datas" :data="table.selectedRecord" @success="modalLeader.success" />
      <Position v-model:visible="modalPosition.visible" :depts="dept.datas" :data="table.selectedRecord" @success="modalPosition.success" />
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { PlusOutlined } from '@ant-design/icons-vue'
  import { message, type TreeProps } from 'ant-design-vue'
  import { computed, onMounted, reactive } from 'vue'

  import { requestAddDeptLeader, requestGetDeptList, requestUserDeptList } from '/@/api/business/company/dept'
  import { DoTypeEnum, IsDeptLeaderEnum } from '/@/api/business/company/dept/enum'
  import { requestUpdateUserStatus } from '/@/api/system/ysys-user/user'
  import { HttpCodeEnum } from '/@/enums/httpEnum'
  import { useQueryPagination } from '/@/hooks/useQueryPagination'
  import { getCompanyInfo } from '/@/storage'

  import Add from './components/Add.vue'
  import Edit from './components/Edit.vue'
  import Leader from './components/Leader.vue'
  import Position from './components/Position.vue'

  const { companyId } = getCompanyInfo()

  /** 组织架构 */
  const dept = reactive({
    visible: false,
    datas: [] as TreeProps['treeData'],
    onSelect: (nodes: number[]) => {
      searchParam.deptId = nodes[0]
      queryList()
    },
  })

  onMounted(() => initDepts())

  /**
   * 初始化组织架构
   */
  const initDepts = async () => {
    const deep = (dept: GetDeptListTypes.IResponse) => {
      return {
        key: dept.deptId,
        title: dept.deptName,
        children: dept.children.map((child: GetDeptListTypes.IResponse) => deep(child)),
      }
    }
    const { responseData } = await requestGetDeptList({ companyId })
    dept.datas = responseData.map((item: GetDeptListTypes.IResponse) => deep(item))
    dept.visible = true
  }

  const setStatus = async (data) => {
    const { userId, userStatus } = data
    const { responseCode } = await requestUpdateUserStatus({ userStatus: userStatus === 1 ? 2 : 1, userId })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success(`${userStatus === 1 ? '冻结' : '恢复'}成功`)
      queryList()
    }
  }

  /** 查询条件 */
  const searchParam = reactive({
    companyId,
    deptId: NaN,
    userName: '',
    userPhone: '',
  })

  /** 表格配置 */
  const table = reactive({
    columns: [
      { title: '姓名', dataIndex: 'userName' },
      { title: '账号', dataIndex: 'userPhone' },
      {
        title: '状态',
        key: 'userStatus',
        dataIndex: 'userStatus',
        filters: [
          {
            text: '正常',
            value: 1,
          },
          {
            text: '冻结',
            value: 2,
          },
        ],
        onFilter: (value, record) => record.userStatus === value,
      },
      {
        title: '岗位',
        dataIndex: 'positionNames',
        customRender: ({ record }) => {
          if (record.positionNames?.length === 0) return '--'
          return record.positionNames.map((item) => item.positionName).join('，')
        },
      },
      { title: '上级', dataIndex: 'userLeaderName', customRender: ({ record }) => record.userLeaderName || '--' },
      { title: '操作', key: 'action' },
    ],
    selectedRecord: {} as UserDeptListTypes.IResponse,
  })

  /** 表格分页hook */
  const { loading, queryList, dataList, pagination, onPaginationChange } = useQueryPagination<UserDeptListTypes.IRequest, UserDeptListTypes.IResponse[]>(searchParam, requestUserDeptList)

  /** 无部门负责人 */
  const noDeptLeader = computed(() => {
    for (let i = 0; i < dataList.value.length; i++) {
      if (dataList.value[i].isDeptLeader === IsDeptLeaderEnum.YES) return false
    }
    return true
  })

  /**
   * 重置
   */
  const clear = () => {
    searchParam.userName = ''
    searchParam.userPhone = ''
  }

  /**
   * 查询
   */
  const search = () => {
    if (isNaN(searchParam.deptId)) {
      message.warning({ content: '请选择组织架构' })
      return
    }
    queryList({ current: 1 })
  }

  /** 新增弹窗 */
  const modalAdd = reactive({
    visible: false,
    success: () => queryList(),
  })

  /**
   * 新增
   */
  const add = () => (modalAdd.visible = true)

  /** 编辑弹窗 */
  const modalEdit = reactive({
    visible: false,
    success: () => queryList(),
  })

  /**
   * 编辑
   * @param record 组织人员
   */
  const edit = (record: UserDeptListTypes.IResponse) => {
    table.selectedRecord = record
    modalEdit.visible = true
  }

  /** 指定上级弹窗 */
  const modalLeader = reactive({
    visible: false,
    success: () => queryList(),
  })

  /**
   * 指定上级
   * @param record 组织人员
   */
  const setLeader = (record: UserDeptListTypes.IResponse) => {
    table.selectedRecord = record
    modalLeader.visible = true
  }

  /**
   * 设为/取消负责人
   * @param record 组织人员
   */
  const setDeptLeader = async (record: UserDeptListTypes.IResponse, doType: DoTypeEnum) => {
    const { responseCode } = await requestAddDeptLeader({
      companyId,
      leaderUserId: record.userId,
      deptId: record.deptList[0].deptId,
      doType,
    })
    if (responseCode === HttpCodeEnum.SUCCESS) {
      message.success(doType === DoTypeEnum.SET ? '设置成功' : '取消成功')
      queryList()
    }
  }

  /** 岗位设置弹窗 */
  const modalPosition = reactive({
    visible: false,
    success: () => queryList(),
  })

  /**
   * 岗位设置
   * @param record 组织人员
   */
  const setPosition = (record: UserDeptListTypes.IResponse) => {
    table.selectedRecord = record
    modalPosition.visible = true
  }
</script>

<style lang="less" scoped>
  .org-person-list {
    display: flex;
  }

  .org {
    width: 200px;
    height: 100%;
    padding: 18px;
    background: #fff;

    .org-title {
      margin-bottom: 12px;
      font-weight: bold;
    }
  }

  .content {
    flex: 1;
  }

  .ssc-search {
    margin-left: 16px;
  }

  .ssc-table {
    margin-left: 16px;

    .dept-leader {
      position: relative;
      top: -2px;
      height: 20px;
      margin-right: 4px;
      padding: 0 8px;
      border: none;
      font-size: 10px;
      background: #87d068;
    }
  }
</style>
